package vn.vietel.pms.business;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;

import org.springframework.transaction.annotation.Transactional;

import vn.vietel.pms.entity.User;
import vn.vietel.pms.entity.exception.ValidationException;
import vn.vietel.pms.service.IUserService;

public class UserServiceImpl implements IUserService {

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	public void delete(User user) {
		User delUser = this.selectUserByUserName(user.getUsername());
		if (delUser != null)
			entityManager.remove(delUser);
	}

	public void deleteByUserName(String userName) {
		User user = this.selectUserByUserName(userName);
		entityManager.remove(user);
	}

	public void saveOrUpdate(User user) throws ValidationException {
		if (user == null) {
			throw new ValidationException("have no user name");
		}
		if (user.getUsername() == null) {
			entityManager.persist(user);
		} else {
			entityManager.merge(user);
		}
	}

	@SuppressWarnings("unchecked")
	public List<User> selectAll() {
		List<User> lists = new ArrayList<User>();
		lists = entityManager.createQuery("SELECT u FROM User u")
				.getResultList();
		return lists;
	}

	public User selectUserByUserName(String userName) {
		try {
			User verify = (User) entityManager.createQuery(
					"SELECT u FROM User u WHERE u.username = :username")
					.setParameter("username", userName).getSingleResult();
			return verify;
		} catch (PersistenceException e) {
			return null;
		}
	}

	public User selectUserByUserName(String userName, String password) {
		try {
			User verify = (User) entityManager.createQuery(
					"SELECT u FROM User u WHERE u.username = :username and "
							+ "u.password = :password").setParameter(
					"username", userName).setParameter("password", password)
					.getSingleResult();
			return verify;
		} catch (PersistenceException e) {
			return null;
		}
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

}
